<template>
  <div class="hello">
    <div class="opea-column">
      <el-button type="primary" icon="el-icon-plus" @click="open()">{{$t('config.createConfig.createConfig')}}</el-button>
    </div>
    <el-table
      v-loading="loading"
      border
      height="620px"
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="name"
        :label="$t('config.table.name')">
      </el-table-column>
      <el-table-column
      :label="$t('opea.opea')"
      width="200">
      <template slot-scope="scope">
        <el-button type="text" size="small" @click="go(scope.row)">{{$t('opea.lookConfig')}}</el-button>
        <el-button type="text" size="small" @click="getInfo(scope.row)">{{$t('opea.info')}}</el-button>
        <el-button type="text" size="small" @click="remove(scope.row)">{{$t('opea.delete')}}</el-button>
      </template>
    </el-table-column>
    </el-table>


    <el-dialog :title="$t(formTitle)" :visible.sync="dialogFormVisible" width="800px" @close="dialogClose()" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item :label="$t('config.form.name')" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('ip.table.server')" :label-width="formLabelWidth" prop="server">
          <el-select v-model="form.server" autocomplete="off" class="my-select">
            <el-option v-for="item in serverList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('config.form.params')" :label-width="formLabelWidth">
          <my-active-form :parameters="allParams" :parametersInfo="allParamsInfo" handler-fn="getResponse" @getResponse="getResPar"></my-active-form>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('opea.cancel')}}</el-button>
        <el-button type="primary" @click="addSubmit()">{{$t('opea.ok')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('delDialog.title')"
      :visible.sync="dialogVisible"
      width="30%">
      <span>{{$t('delDialog.message')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{$t('opea.cancel')}}</el-button>
        <el-button type="primary" @click="del()">{{$t('opea.ok')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import myActiveForm from './activeForm'
import {resetForm , decToHex} from '../handle'
export default {
  name: 'config',
  components:{myActiveForm},
  data () {
    return {
      serverList:[],
      allParams:[],
      allParamsInfo:[],
      resParams:[],
      tableData:[],
      form:{},
      removeId:0,
      dialogVisible:false,
      formLabelWidth:'120px',
      dialogFormVisible:false,
      formTitle:'config.form.addTitle',
      formType:'create',
      rules:{
        name:[
          {required:true, message: this.$t('validate.input.name'), trigger: 'change'}
        ],
        server:[
          {required:true, message: this.$t('validate.select.server'), trigger: 'change'}
        ]
      },
      loading:false
    }
  },
  mounted(){
    this.getTableData()
    this.getParams()
    this.getSelect()
  },
  methods:{
    getSelect(){
      this.$axios.get('m/q/i')
      .then(res=>{
        this.serverList = res.data
      })
    },
    // 获取所有有效参数
      getParams(){
        this.$axios.get('/m/q/p')
        .then(res=>{
          res.data.forEach((v,k)=>{
            v.show = true
          })
          res.data = res.data.filter(v=>{
            if(v.code !=10 && v.code != 11){
              return v
            }
          })
          this.allParams = res.data
        })
      },
      IP(number){
        return (number >> 24 &0xff) + '.' + (number >> 16 & 0xff) +'.'+ (number >> 8 & 0xff) +'.'+ (number & 0xff)
      },
    // 查询配置明细
    getInfo(row){
      this.formType = 'edit'
      resetForm(this,'form')
      this.allParamsInfo = []
      this.formTitle = 'config.form.editTitle'
      this.$axios.get('/m/q/c?'+row.id)
      .then(res=>{
        // let data = {name:res.data.name,server:res.data.protocol}
        if(res.data.parameters){
          res.data.parameters = res.data.parameters.map(v=>{
            let val = v.param_value;
            if(v.param_code == 10){
              val = this.IP(v.param_value)
            }else if(v.param_code == 6||v.param_code == 8 || (v.param_code >= 16 && v.param_code <= 33) || (v.param_code >= 39 && v.param_code <=47)){
              val = decToHex(v.param_value)
            }
            return {id:v.id, config_id: v.config_id, c:v.param_code, v:val  ,name:v.param_name,chinese:v.param_chinese}
          })
          console.log(res.data.parameters)
        }
        this.allParamsInfo = res.data.parameters
        let arr = [];
            this.allParams.forEach(v=>{
              if(this.allParamsInfo){
                this.allParamsInfo.forEach(r=>{
                    if(r.c == v.code){
                        arr.push(r.c)
                    }
                })
              }
                
            })
            this.allParams.forEach(v=>{
                if(arr.indexOf(v.code) > -1){
                    v.show = false
                    return
                }
                v.show = true
            })
            this.serverList.forEach(v=>{
              if(v.id == res.data.ip_config){
                res.data.server = v.id
              }
            })

        this.form = Object.assign({},res.data)
      })
      this.dialogFormVisible = true;
    },
    // 获取所有配置
    getTableData(){
      this.loading = true;
      this.$axios.get('/m/q/c')
      .then(res=>{
        this.loading = false;
        this.tableData = res.data ? res.data : []
      })
      .catch(err=>{
        this.loading = false;
      })
    },
    open(){
      this.formType = 'create'
      this.formTitle = 'config.form.addTitle'
      resetForm(this,'form')
      this.allParamsInfo = [];
      this.getParams()
      this.dialogFormVisible = true
    },
    remove(row){
      this.removeId = row.id;
      this.dialogVisible = true;
    },
    // 删除配置
    del(){
      this.$axios.delete('/m/d/c?'+this.removeId)
      .then(res=>{
        if(res.status == 202){
          this.$message.success(res.statusText)
          this.getTableData()
        }
      })
      .catch(err=>{
        if(err){
          this.$message.error(err.data.message)
        }
      })
    this.dialogVisible = false;
    },
    // 获取动态参数
    getResPar(data){
      this.resParams = data;
    },
    //方式一 利用map判断
    isExistInObj1(arr,key) {
      var arrNum = [];
      var flag;
      var mapArr= arr.map(item=>item[key]);
      var setArr = new Set(arrNum);//去重复
      flag=setArr.size<mapArr.length?true:false;
      return flag;
    },
    addSubmit(){
        this.$refs['form'].validate(valid=>{
            if(!valid){
                return
            }
            // 判断参数名是否重复
            // if(this.isExistInObj1(this.resParams,'c')){
            //   this.$message.error('参数名不能重复')
            //   return
            // }
            let data = {n:this.form.name}
            data.p = []
            // 添加时该转的转为整数
            var startReg = /^0x/, dotNumber = /^\d+\,\d+$/,max,min;
            this.resParams.forEach(v=>{
              if(v.c == 6||v.c == 8 || (v.c >= 16 && v.c <= 33) || (v.c >= 39 && v.c <=47)){
                if(startReg.test(v.v)){
                    v.v = Number(v.v)
                }else if(dotNumber.test(v.v)){
                    max = v.v.substring(0,v.v.indexOf(','));
                    min = v.v.substring(v.v.indexOf(',')+1)
                    v.v = (max << 16)  | (min & 0xffff)
                }
              }
              data.p.push(v)
            })
            // data.p = this.resParams
            data.i = this.form.server
            if(this.formType === 'edit'){
              data.p.forEach(v=>{
                delete v.chinese
                delete v.config_id
                delete v.id
                delete v.name
              })
              data.a = 'update'
            }
            this.$axios.post('/m/a/c',data)
            .then(res=>{
              if(res.status == 201 || res.status == 200){
                this.$message.success(res.statusText)
                this.getTableData()
              }
              this.dialogFormVisible = false;
            })
            .catch(err=>{
              this.$message.error(err.data.message)
            })
        })
    },
    dialogClose(){
      this.allParams.forEach(v=>{
        v.show = false
      })
    },
    go(row){
      this.$router.push({path:'/config-map',query:{id:row.id}})
    }
  }
}
</script>
<style scoped>
.opea-column{
  margin-bottom: 15px;
}
</style>


